import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtils {

    /**
     * 从URL下载图片并保存到指定路径
     * @param url 图片的网络URL
     * @param savePath 本地保存路径
     * @throws IOException 可能的IO异常
     */
    public static void saveImage(String url, String savePath) throws IOException {
        URL imageUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        
        // 检查响应码，只有200表示成功
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException("无法连接到图片资源，响应码：" + connection.getResponseCode());
        }
        
        // 检查内容类型是否为图片
        String contentType = connection.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IOException("URL指向的不是图片资源，类型：" + contentType);
        }
        
        try (InputStream in = connection.getInputStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 检查目录是否存在，不存在则创建
     * @param dirPath 目录路径
     */
    public static void ensureDirectoryExists(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                System.out.println("创建目录成功：" + dirPath);
            } else {
                System.err.println("创建目录失败：" + dirPath);
            }
        }
    }

    /**
     * 将下载记录追加到日志文件
     * @param log 日志内容
     */
    public static void appendLog(String log) {
        try (BufferedWriter writer = new BufferedWriter(
                new FileWriter("download_log.txt", true))) {
            writer.write(log);
            writer.newLine();
        } catch (IOException e) {
            System.err.println("记录日志失败：" + e.getMessage());
        }
    }
}
